import uuid

from flask import Blueprint,request,make_response,jsonify,redirect
import json, random, time, requests
from utils.myredis import r
from models.models import *

serve_blue = Blueprint("serveblue",__name__)

@serve_blue.route("/qneed",methods=["POST"])
# 抢需求
def qneed():
    data = json.loads(request.data)
    jdr = data["userid"]
    code = data["code"]
    # hash取模
    number = hash(int(code)) % 3
    if number == 0:
        res = Need.query.filter_by(code=code).first()
        if res:
            res.status = 3,
            res.jdid = jdr
            db.session.add(res)
            db.session.commit()
        return jsonify({"code": 200, "msg": "已抢"})
    else:
        needs = "Need" + str(number)
        needs = globals().get(f'{needs}')
        res = needs.query.filter_by(code=code).first()
        if res:
            res.status = 3,
            res.jdid = jdr
            db.session.add(res)
            db.session.commit()
        return jsonify({"code":200,"msg":"已抢"})

# 获取当前用户的需求
@serve_blue.route("/userneed")
def userneed():
    userid = int(request.args.get("userid"))
    ret = db.session.execute("select *  from (select * from need where status=3 and jdid=%d union all select * from need1 where status=3 and jdid=%d union all select * from need2 where status=3 and jdid=%d) as t;"%(userid,userid,userid))
    lst = []
    for i in ret:
        lst.append({
            'code': str(i.code),
            'title': i.title,
            "money": i.money,
            "described": i.described,
            "closeid": i.closeid,
            "userid": i.userid
        })
    return jsonify({"code":200,"msg":"获取成功","data":lst})

# 用户提交需求
@serve_blue.route("/tjneed")
def tjneed():
    code = request.args.get("code")
    number = hash(int(code)) % 3
    tname = "Need"
    if number != 0:
         tname = tname + str(number)
    # 转为表名
    tablename = globals().get(f'{tname}')
    r = tablename.query.filter_by(code=code).first()
    if r:
        r.status = 4
        db.session.add(r)
        db.session.commit()
        return jsonify({"code": 200, "msg": "提交成功"})

# 获取服务商已提交的需求
@serve_blue.route("/funeed")
def funeed():
    userid = int(request.args.get("userid"))
    ret = db.session.execute("select *  from (select * from need where status=4 and userid=%d union all select * from need1 where status=4 and userid=%d union all select * from need2 where status=4 and userid=%d) as t;"%(userid,userid,userid))
    lst = []
    for i in ret:
        lst.append({
            'code': str(i.code),
            'title': i.title,
            "money": i.money,
            "described": i.described,
            "closeid": i.closeid,
            "userid": i.userid,
            "jdid":i.jdid
        })
    return jsonify({"code": 200, "msg": "获取成功", "data": lst})

# 雇主提交支付佣金
@serve_blue.route("/zfneed")
def zfneed():
    jdid = request.args.get("jdid")
    userid = request.args.get("userid")
    money = request.args.get("money")
    code = request.args.get("code")
    # print(jdid,userid,money)
    if not all([jdid,userid,money,code]):
        return jsonify({"code": 400, "msg": "字段不能为空"})
    user = User.query.filter_by(id=jdid).first()
    if user:
        # 更新服务商的金额
        user.money = float(user.money) + float(money)
        db.session.add(user)
        db.session.commit()
        users = User.query.filter_by(id=userid).first()
        if users:
            # 更新雇主的锁定金额
            users.locks = float(users.locks) - float(money)
            db.session.add(users)
            db.session.commit()
            # 修改需求状态
            # print(code)
            number = hash(int(code)) % 3
            tname = "Need"
            if number != 0:
                tname = tname + str(number)
            # 转为表名
            tablename = globals().get(f'{tname}')
            r = tablename.query.filter_by(code=code).first()
            if r:
                r.status = 5
                db.session.add(r)
                db.session.commit()
                return jsonify({"code":200,"msg":"支付成功"})

# 获取全部商品
@serve_blue.route("/getgoods")
def getgoods():
    goods = Goods.query.filter_by(status=1).all()
    lst = []
    if goods:
        for i in goods:
            lst.append({
                "id":i.id,
                "title":i.title,
                "price":i.price,
                "userid":i.userid,
                "count":i.count
            })
    return jsonify({"code":200,"data":lst})

# 加入Hash购物车
@serve_blue.route("/setgwc")
def setgwc():
    userid = request.args.get("userid")
    goodsid = request.args.get("goodsid")
    if not all([userid,goodsid]):
        return jsonify({"code": 400, "msg": "字段不能为空"})
    goods = Goods.query.filter_by(id=goodsid).first()
    if goods.count < 1:
        return jsonify({"code": 400, "msg": "库存不足"})
    pkey = "gwc" + str(userid)
    # 判断该商品在购物车中是否存在
    num = r.hash_getone(pkey,goodsid)
    if num:
        # print(num.decode())
        num = int(num.decode())
        # 添加购物车数量加1
        r.hash_add(pkey,goodsid,str(num+1))
        return jsonify({"code": 200, "msg": "购买数量加1"})
    else:
        r.hash_add(pkey, goodsid, 1)
        return jsonify({"code": 200, "msg": "加入购物车成功"})

# 获取购物车
@serve_blue.route("/getgwc")
def getgwc():
    userid = request.args.get("userid")
    pkey = "gwc" + str(userid)
    res = r.hash_getall(pkey)
    lst =[]
    for i, j in res.items():
        # 获取商品数量
        num = j.decode()
        goodsid = i.decode()
        res = Goods.query.filter_by(id=goodsid).first()
        lst.append({
            "id":res.id,
            "title":res.title,
            "price":res.price,
            "userid":res.userid,
            "count":res.count,
            "min":num
        })
    return jsonify({"code": 200, "msg": "ok", "data": lst})

# 接口幂等性  解决重复生成订单
@serve_blue.route("/gettoken")
def gettoken():
    # 生成token
    token = uuid.uuid1().hex
    # print(token)
    # 将token存入redis
    r.str_add(token,'1')
    return jsonify({"code":200,"token":token})

# 购买
@serve_blue.route("/gm",methods=["POST"])
def gm():
    data = json.loads(request.data)
    checkList = data["checkList"]
    tokens = data["token"]
    red = r.str_get(tokens)
    if not red:
        return jsonify({"code":400,"msg":"不能频繁操作"})
    r.del_key(tokens)
    userid = data["userid"]
    pkey = "gwc" + str(userid)
    for i in checkList:
        # 获取购买数量
        num = r.hash_getone(pkey, i)
        # 查询商品价格
        goods = Goods.query.filter_by(id=i).first()
        # 获取消费金额
        count= goods.price * float(num.decode())
        # 订单号
        number = str(int(time.time())) + str(userid) + str(random.randint(10000, 99999))
        # 添加订单
        goo = Goodsorders(number=number,userid=userid,goodsid=i,money=count)
        db.session.add(goo)
        db.session.commit()
        # 修改卖家用户金额
        user = User.query.filter(User.id==goods.userid).first()
        if user:
            user.money = user.money + float(count)
            db.session.add(user)
            db.session.commit()
        # 修改买家金额
        users1 = User.query.filter_by(id=userid).first()
        if users1:
            users1.money = users1.money - float(count)
            db.session.add(users1)
            db.session.commit()
        # 修改商品库存
        goods.count = goods.count - int(num.decode())
        db.session.add(goods)
        db.session.commit()
        # 删除缓存
        r.del_onehash(pkey,i)
    return jsonify({"code":200,"msg":"支付成功"})


# # 实现最近浏览
@serve_blue.route('/browsing',methods=["POST"])
def browsing():
    data = json.loads(request.data)
    userid = data["userid"]
    code = data["code"]
    title = data["title"]
    price = data["price"]
    described = data["described"]
    key = 'user' + str(userid) + 'goods' + str(code)
    r.hash_add(key, 'code', code)
    r.hash_add(key, 'title', title)
    r.hash_add(key, 'described', described)
    r.hash_add(key, 'price', price)
    return jsonify({'code':200})

# 获取最近浏览数据
@serve_blue.route('/getbrowsing')
def getbrowsing():
    userid = request.args.get('userid')
    key = 'user' + str(userid) + '*'
    lst = r.getvalues(key)
    reslst = []
    for i in lst:
        goods = r.hash_getall(i)
        dict = {}
        for k, v in goods.items():
            kk = k.decode()
            vv = v.decode()
            dict[kk] = vv
        reslst.append(dict)
    return jsonify({'code': 200, 'data': reslst})